<?php
/***********************************************************
 * @网站导航
 * @作者 pcfcms <1131680521@qq.com>
 * @主页 http://www.pcfcms.com
 * @时间 2021年01月01日
***********************************************************/
namespace app\admin\controller;
use think\facade\Db;
use think\facade\Session;
use think\facade\Request;
use think\facade\Cache;
use app\admin\logic\NavLogic;
class Nav extends Base
{
    public $NavLogic;
    public $popedom;
    public function _initialize() {
        parent::_initialize();
        $this->NavLogic = new NavLogic();
        $ctl_act = strtolower(Request::controller().'/index');
        $this->popedom = appfile_popedom($ctl_act);
    }

    public function index()
    {
        //验证查看权限
        if(!$this->popedom["list"]){
            return $this->Notice(config('params.auth_msg.list'),true,3,false);
        }
        if (Request::isAjax()) {
            // 导航位置数据
            $order = 'sort_order asc, position_id asc';
            $PosiData1 = Db::name('nav_position')->order($order)->select()->toArray();
            // 导航位置ID
            $position_id1 = input('param.position_id/d') ? input('param.position_id/d') : 0;
            $position_id1 = empty($position_id1) && !empty($PosiData1) ? $PosiData1[0]['position_id'] : $position_id1;
            $position_name1 = '指向菜单';
            foreach ($PosiData1 as $key => $value) {
                if ($value['position_id'] == $position_id1) {
                    $position_name1 = $value['position_name'];
                    break;
                }
            }
            $nav_list = array();
            // 目录列表
            $where = [];
            $where[] = ['position_id','=',$position_id1];
            $nav_list = $this->NavLogic->nav_list(0, 0, false, 0, $where, false);
            foreach ($nav_list as $key=>$val){
                if($val['arctype_sync']>0){
                    $nav_list[$key]['nav_name'] = $val['nav_name']."<font style='color:red;'>【已同步分类栏目】</font>";
                }
                $nav_list[$key]['position_name'] = $position_name1;
            }
            $nav_list = array_merge($nav_list);
            if($nav_list){
                $result = ['code' => 0, 'msg' => 'ok','data' => $nav_list];
                return json($result);            
            }else{
                $result = ['code' => 1, 'msg' => 'no','data' =>''];
                return json($result);       
            }
        }
        // 导航位置数据
        $order = 'sort_order asc, position_id asc';
        $PosiData = Db::name('nav_position')->order($order)->select()->toArray();
        $AssignData['posipata'] = $PosiData;
        // 导航位置ID
        $position_id = input('param.position_id/d') ? input('param.position_id/d') : 0;
        $position_id = empty($position_id) && !empty($PosiData) ? $PosiData[0]['position_id'] : $position_id;
        $AssignData['position_id'] = $position_id;
        // 菜单最多级别
        $nav_max_level = config('pcfcms.nav_max_level');
        $this->assign('nav_max_level', $nav_max_level);
        $this->assign($AssignData);
        return $this->fetch();
    }

    // 新增
    public function add()
    {
        if (Request::isAjax()) {
            //验证权限
            if(!$this->popedom["add"]){
                if(config('params.auth_msg.test')){
                    $result = ['status' => false, 'msg' => config('params.auth_msg.pcfcms')];
                    return $result;
                }else{
                    $result = ['status' => false, 'msg' => config('params.auth_msg.add')];
                    return $result;                    
                }
            }
            $post = input('param.');
            if (!empty($post)) {
                if (empty($post['arctype_sync'])) {
                    if (empty($post['nav_name'])) return ['status' => false, 'msg' => '请填写导航名称'];
                    if (empty($post['nav_url'])) return ['status' => false, 'msg' => '请填写导航链接'];
                }
                // url格式化
                $post['nav_url'] = htmlspecialchars_decode($post['nav_url']);
                // 根据菜单ID获取最新的最顶级菜单ID
                if (intval($post['parent_id']) > 0) {
                    $navig_row = Db::name('nav_list')->field('nav_id,topid')->where('nav_id', $post['parent_id'])->find();
                    $post['topid'] = !empty($navig_row['topid']) ? $navig_row['topid'] : $navig_row['nav_id'];
                }
                $newData = array(
                    'sort_order' => 100,
                    'target'    => !empty($post['target']) ? 1 : 0,
                    'nofollow'    => !empty($post['nofollow']) ? 1 : 0,
                    'add_time'  => getTime(),
                    'update_time'  => getTime()
                );
                unset($post['file']);
                $data = array_merge($post, $newData);
                $insertId = Db::name('nav_list')->save($data);
                if($insertId){
                    Cache::delete('nav_list');
                    return ['status' => true, 'msg' => '操作成功!','url' =>url('/nav/index',['position_id'=>$post['position_id']])->suffix(true)->domain(true)->build()]; 
                }
            }
            return ['status' => false, 'msg' => '操作失败'];
        }
        $ReturnData = [];
        // 导航位置
        $position_id = input('param.position_id/d') ? input('param.position_id/d') : 0;
        if (empty($position_id)) return $this->Notice('请选择导航位置',false,3,false);
        $AssignData['PosiData'] = Db::name('nav_position')->where('position_id', $position_id)->find();
        // 所属菜单
        $parent_id = input('param.parent_id/d');
        $grade = 0;
        $pnavname = '';
        if ($parent_id > 0 && !empty($parent_id)) {
            $info = Db::name('nav_list')->where('nav_id',$parent_id)->find();
            if ($info) {
                $grade = $info['grade'] + 1;//级别
                $pnavname = $info['nav_name'];//上级菜单名称
            }
        }
        $AssignData['grade'] = $grade;
        $AssignData['parent_id'] = $parent_id ? $parent_id : 0;
        $AssignData['pnavname'] = $pnavname;
        // 前台功能下拉框
        $AssignData['Function'] =  $this->NavLogic->ForegroundFunction();
        // 全部栏目下拉框
        $AssignData['ArctypeHtml'] = $this->NavLogic->GetAllArctype();
        $this->assign($AssignData);
        return $this->fetch();
    }

    // 编辑
    public function edit()
    {
        if (Request::isAjax()) {
            //验证权限
            if(!$this->popedom["modify"]){
                if(config('params.auth_msg.test')){
                    $result = ['status' => false, 'msg' => config('params.auth_msg.pcfcms')];
                    return $result;
                }else{
                    $result = ['status' => false, 'msg' => config('params.auth_msg.modify')];
                    return $result;                    
                }
            }  
            $post = input('param.');
            unset($post['file']);
            if(!empty($post)){
                if (empty($post['arctype_sync'])) {
                    if (empty($post['nav_name'])) return ['status' => false, 'msg' => '请填写导航名称'];
                    if (empty($post['nav_url'])) return ['status' => false, 'msg' => '请填写导航链接'];
                }
                // url格式化
                $post['nav_url'] = htmlspecialchars_decode($post['nav_url']);
                // 当前更改的等级
                $grade = 0; 
                // 根据菜单ID获取最新的最顶级菜单ID
                if (intval($post['parent_id']) > 0) {
                    $nav_row = Db::name('nav_list')->field('nav_id,grade,topid')->where('nav_id', $post['parent_id'])->find();
                    $grade = $nav_row['grade'] + 1;
                    $post['topid'] = !empty($nav_row['topid']) ? $nav_row['topid'] : $nav_row['nav_id'];
                }
                $newData = array(
                    'grade' => $grade,
                    'arctype_sync'  => !empty($post['arctype_sync']) ? 1 : 0,
                    'target'    => !empty($post['target']) ? 1 : 0,
                    'nofollow'    => !empty($post['nofollow']) ? 1 : 0, 
                    'add_time'  => getTime(),
                    'update_time'  => getTime()
                );
                $data = array_merge($post, $newData);
                $ResultID = Db::name('nav_list')->save($data);
                if($ResultID){
                    return ['status' => true, 'msg' => '操作成功!','url' =>url('/nav/index', ['position_id'=>$post['position_id']])->suffix(false)->domain(true)->build()]; 
                }
            }
            return ['status' => false, 'msg' => '操作失败'];
        }
        $ReturnData = [];
        // 导航位置
        $nav_id = input('param.nav_id/d') ? input('param.nav_id/d') : 0;
        if (empty($nav_id)) return $this->Notice('请选择导航',true,3,false);
        $field = 'a.*, b.position_name, c.typename';
        $NavList = Db::name('nav_list')
                    ->field($field)
                    ->alias('a')
                    ->join('nav_position b', 'a.position_id = b.position_id', 'LEFT')
                    ->join('arctype c', 'a.type_id = c.id', 'LEFT')
                    ->where('a.nav_id', $nav_id)
                    ->find();
        $NavList['nav_name'] = !empty($NavList['arctype_sync']) ? $NavList['typename'] : $NavList['nav_name'];
        $AssignData['NavList'] = $NavList;
        // 是否有子菜单
        $hasChildren = $this->NavLogic->hasChildren($nav_id);
        if ($hasChildren > 0) {
            $select_html = Db::name('nav_list')->where('nav_id', $NavList['parent_id'])->value('nav_name');
            $select_html = !empty($select_html) ? $select_html : '顶级菜单';
        } else {
            // 所属菜单
            $select_html = '<option value="0" data-grade="-1">顶级菜单</option>';
            $selected = $NavList['parent_id'];
            $nav_max_level = config('pcfcms.nav_max_level');
            $options = $this->NavLogic->nav_list(0, $selected, false, $nav_max_level - 1);
            foreach ($options AS $var){
                $select_html .= '<option value="' . $var['nav_id'] . '" data-grade="' . $var['grade'] . '"';
                $select_html .= ($selected == $var['nav_id']) ? "selected='true'" : '';
                $select_html .= ($nav_id == $var['nav_id']) ? "disabled='true' style='background-color:#f5f5f5;'" : '';
                $select_html .= '>';
                if ($var['level'] > 0){
                    $select_html .= str_repeat('&nbsp;', $var['level'] * 4);
                }
                $select_html .= htmlspecialchars(addslashes($var['nav_name'])) . '</option>';
            }
        }
        $this->assign('select_html',$select_html);
        $this->assign('hasChildren',$hasChildren);
        // 前台功能下拉框
        $AssignData['Function'] =  $this->NavLogic->ForegroundFunction();
        // 全部栏目下拉框
        $AssignData['ArctypeHtml'] = $this->NavLogic->GetAllArctype($NavList['type_id']);
        $this->assign($AssignData);
        return $this->fetch();
    }

    // 删除
    public function del()
    {
        if (Request::isAjax()) {
            //验证权限
            if(!$this->popedom["delete"]){
                if(config('params.auth_msg.test')){
                    $result = ['status' => false, 'msg' => config('params.auth_msg.pcfcms')];
                    return $result;
                }else{
                    $result = ['status' => false, 'msg' => config('params.auth_msg.delete')];
                    return $result;                    
                }
            } 
            $nav_id = input('param.del_id/d');
            $grade = Db::name('nav_list')->where('nav_id','=',$nav_id)->value('grade');
            if($grade <= 0){
                if (Db::name('nav_list')->where('nav_id|topid','=',$nav_id)->delete()) {
                    $result = ['status' => true, 'msg' => '删除成功'];
                    return $result;
                } else {
                    $result = ['status' => false, 'msg' => '删除失败'];
                    return $result;
                }
            }else{
                if (Db::name('nav_list')->where('nav_id|parent_id','=',$nav_id)->delete()) {
                    $result = ['status' => true, 'msg' => '删除成功'];
                    return $result;
                } else {
                    $result = ['status' => false, 'msg' => '删除失败'];
                    return $result;
                }                
            }
            return $result;
        }       
    }
}